package com.bosch.in.rtp1.ept.manager.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;

import com.bosch.in.rtp1.ept.dao.ActiveHoldDiagramDao;
import com.bosch.in.rtp1.ept.manager.ActiveHoldDiagramManager;
import com.bosch.in.rtp1.ept.model.dto.BoxPlotFactor;
import com.bosch.in.rtp1.ept.util.DaoFactory;
import com.bosch.in.rtp1.ept.util.ehcache.EhcacheFactory;


public class ActiveHoldDiagramManagerImpl implements ActiveHoldDiagramManager {

	/**
	 * used to manage connection
	 */
	private DBConnectionManager dbManager;
	/**
	 * DAO object to get Active Hold data.
	 */
	private ActiveHoldDiagramDao activeHoldDiagramDao;
	
	public static final String CACHE_KEY = "ActiveHoldDiagramManagerImpl";
	
	private static final Logger LOGGER = Logger.getLogger(ActiveHoldDiagramManagerImpl.class);
	
	/**
	 * Look up datasource to get connection from pre-initialized connection pool
	 * @throws Exception
	 */
	public ActiveHoldDiagramManagerImpl() { 
	}

	/**
	 * lazy initialize connection when we really need to interact with database and in case 
	 * data can't be found in caching system.
	 * @throws SQLException
	 */
	private void init() throws SQLException {
		if (dbManager == null) {
			dbManager = new DBConnectionManager();
			activeHoldDiagramDao = DaoFactory.getInstance().getActiveHoldDiagramDao(dbManager.getConnection());
		}
	}

	@Override
	public List<BoxPlotFactor> getFactorList() throws SQLException {
		LOGGER.debug("Begin getFactorList");
		try
		{
			// lazy init connection
			init();
			List<BoxPlotFactor> boxPlotFactors =  activeHoldDiagramDao.getFactorList();
			EhcacheFactory.getActHldcacheWrapper().put(CACHE_KEY, boxPlotFactors);
			
			return boxPlotFactors;
		}
		finally
		{
			dbManager.close();
			LOGGER.debug("Closed connection");
			LOGGER.debug("End getFactorList");
		}
	}

	@Override
	public List<BoxPlotFactor> getFactorListToExport() throws SQLException {
		LOGGER.debug("Begin getFactorListToExport");
		List<BoxPlotFactor> boxPlotFactors =  EhcacheFactory.getActHldcacheWrapper().get(CACHE_KEY);
		if (boxPlotFactors == null) {
			boxPlotFactors = getFactorList();
		}
		
		LOGGER.debug("End getFactorListToExport");
		return boxPlotFactors;
	}
	
}
